<template>
	<view class="orderDetails">	
		<nav-bar title="订单详情"></nav-bar>
		<cancel-order ref="cancelOrder" @done="initInfo" v-if="details.status===0" :info="details"></cancel-order>
		<view class="top-status flex-btw">
			<view class="status">
				{{orderStatus}}
			</view>
			<view class="payment" v-if="details.status == 0" @click="payState = true">立即支付</view>
			<view class="open-code" v-if="details.picking_code && [1,2].indexOf(details.status) !== -1 " @click="showCode = true">自提码</view>
		</view>
		<view class="orderDetails-state">
			<block v-if="details.type === 1">
				<!-- <view class="code">
					<text class="hint">自提码:</text>
					<text class="number">{{details.picking_code}}</text>
				</view> -->
				<swiper :circular="true" style="height: 270rpx;" :disable-touch="true">
					<swiper-item v-for="item in shops" :key="item.id">
						<view class="self">
							<view class="hint">
								<u-icon name="map"></u-icon>
								<text>自提地址</text>
							</view>
							<view class="detail">
								{{item.address}}
							</view>
							<view class="hint">
								<text class="distance">当前位置距离门店 {{item.distanceText}}</text>
								<text class="look-map" @click="openMap(item)">查看地图</text>
							</view>
						</view>
					</swiper-item>
				</swiper>
			</block>
			<view class="user" v-else>
				<image class="user-icon" mode="aspectFit" :src="`${STATIC_URL}/logistics/address.png`"></image>
				<view class="user-info">
					<view class="top">
						<view class="info-name"> {{ details.name }} </view>
						<view class="info-tel">{{ details.phone }}</view>
					</view>
					<view class="address">
						{{ details.address }} {{ details.address_detail }}
					</view>
				</view>
			</view>
		</view>
		<view class="orderDetails-order">
			<view class="title">
				<image class="icon" mode="aspectFit" :src="`${STATIC_URL}/bag.png`" />
				<view class="text">订单信息</view>
			</view>
			<view class="bd">
				<template v-for="item in details.order_goods">
					<order-item :key="item.id" :item="item"> </order-item>
				</template>
				<view class="pay"> 实付：¥ {{ details.money }} </view>
				<view class="oper">
					<!-- <view class="btn"> 申请退款 </view> -->
				</view>
			</view>
		</view>

		<view class="orderDetails-info">
			<view class="row">订单编号：{{ details.order_num }}</view>
			<view class="row">支付方式：{{ details.pay ? "微信" : "余额" }}支付</view>
			<view class="row">物流公司：{{ details.shipping_name }}</view>
			<view class="row">快递单号：{{ details.shipping_number
        }}
				<view class="copy" @click="copy" v-if="details.shipping_number">复制</view>
			</view>
			<view class="row">
				下单时间：{{ timeFormat(details.createtime, "Y/M/D h:m") }}
			</view>
			<view class="row">
				发货时间：{{ timeFormat(details.shipping_time, "Y/M/D h:m") || "" }}
			</view>
		</view>
		<view style="padding-bottom: 10rpx;background: #EDEFF1;" class="flex flex-jc-c" v-if="ischeckProfit">
			<image @click="show = true" src="https://xy.outletds.com/uploads/icon/cash.png" style="width: 100%;height: 270rpx;"></image>
		</view>
		<products></products>
		<view style="height: 100rpx;"></view>
		<view class="orderDetails-oper">
			<view class="btn check" v-if="details.status == 0" @click="orderCancel">取消订单</view>
			<template v-if="details.status == 2">
				<!-- <view class="btn check" @click.stop="logisticsNavigate">
          查看物流 -->
				<!-- </view> -->
				<view class="btn confirm" @click.stop="confirm"> 确认收货 </view>
			</template>
		</view>
		<u-action-sheet :list="payList" v-model="payState" @click="payClick"></u-action-sheet>
		<code-popup :value.sync="showCode" title="请向核销员出示" :src="details.picking_code_qrcode"></code-popup>
		
		<activity @rejectProfit="rejectProfit" :rebateMoney="rebate_money" :show='show' @receive="receive" />
	</view>
</template>

<script>
	import {
		orderDetails,
		shoppingCarDel,
		stateUpdate,
		statePay,
		returnDetails,
	} from "@/utils/api";
	import { rejectProfitApi,acceptProfitApi,checkProfitApi } from '@/api/my.js'
	import {
		distanceApi
	} from "@/api/index.js"
	import OrderItem from "@/components/order/order";
	import {
		mapGetters
	} from "vuex";
	import {
		formatTime
	} from "@/utils/time";
	import CodePopup from "@/components/code-popup.vue"
	import CancelOrder from "./components/cancel_order.vue"
	import Products from './components/products.vue'
	import activity from '@/components/activity.vue';
	let timer = null
	export default {
		components: {
			OrderItem,
			CodePopup,
			CancelOrder,
			Products,
			activity
		},
		computed: {
			...mapGetters(["bagsRecord"]),
			orderStatus(){
				let str = ""
				if(Object.keys(this.details).length){
					switch(this.details.status){
						case 0:
							str = "等待支付"
							break
						case 1:
							str = this.details.picking_code ? "等待自提" : "等待发货"
							break
						case 2:
							str = this.details.picking_code ? '等待自提' : "待收货"
							break
						case 3:
							str = "交易成功"
							break;
						case 5:
							str= "交易关闭"
					}
					return str
				}else{
					return ""
				}
			}
		},
		onUnload() {
			clearInterval(timer)
			clearInterval(paytimer)
			paytimer = null
			timer = null
		},
		data() {
			return {
				rebate_money: 0,
				ischeckProfit: false,
				show: false,
				id: "", // 订单id
				type: "", // 订单类型
				details: {}, // 订单信息
				payList: [{
						text: "余额支付",
						value: 0,
					},
					{
						text: "微信支付",
						value: 1,
					},
				],
				payState: false,
				shops: [],
				showCode: false,
				id: null
			};
		},
		onLoad({
			id
		}) {
			this.id = id;
			this.initInfo();
			// 删除购物车下单成功订单
			let pages = getCurrentPages()
			let pre = pages[pages.length - 2]; // 上一页为orderConfirm
			// orderConfirm 下单成功使用redirectTo 会从页面栈中移除
			if (pre && pre.route == "pages/tabs/bag/bag") {
				console.log("bags=======", pre);
				// pre.$vm.dropBag(); //
				shoppingCarDel({
					id: this.bagsRecord,
				}).then((resp) => {
					console.log("删除购物车", resp);
				});
			}
		},
		methods: {
			//领取
			async receive() {
				const res = await acceptProfitApi({
					id: this.id
				})
				if(res.code == 200) {
					uni.showToast({
						title: '领取成功',
						icon: 'none',
						duration: 2000,
						success() {
							this.show = false
							uni.navigateTo({
								url: '/pages/me/line_up_order?type=1' 
							})
						}
					})
				}
			},
			//拒绝权益
			async rejectProfit() {
				const res = await rejectProfitApi({
					id: this.id
				})
				if(res.code == 200) {
					this.show = false
					this.ischeckProfit = false
				}
			},
			//检查权益
			async checkProfit() {
				const res = await checkProfitApi()
				if(res.data.show_flag === 1) {
					this.ischeckProfit = true
					this.rebate_money = res.data.rebate_money || 0
					this.id = res.data.id
					/* clearInterval(timer)
					timer = null */
				}
			},
			// 复制
			copy() {
				uni.setClipboardData({
					data: this.details.shipping_number,
					success: () => {
						uni.showToast({
							icon: "none",
							title: "已复制到剪贴板",
						});
					},
				});
			},
			timeFormat(time, str) {
				return formatTime(time, str);
			},
			initInfo() {
				let _this = this;
				orderDetails({
					id: this.id,
				}).then((resp) => {
					if (resp.code == 200) {
						this.details = resp.data
						
						if(resp.data.status == 3) {
							setTimeout(() => {
								this.checkProfit()
							},2000)
						}
					}
				});
				this.initDistance()
			},
			async initDistance() {
				// 计算用户地址
				// #ifdef H5
				distanceApi().then(({
					data
				}) => {
					this.shops = data
				})
				// #endif
				// #ifdef MP-WEIXIN
				// 获取定位授权
				uni.authorize({
					scope: 'scope.userLocation',
					success: (res) => {
						uni.getLocation({
							type: 'wgs84',
							success: (res) => {
								distanceApi({
									lng: res.longitude,
									lat: res.latitude
								}).then(({
									data
								}) => {
									this.shops = data
								})
							},
							fail: (err) => {
								console.log('失败了');
								console.log(err);
							}
						})
					},
					fail: (err) => {
						console.log('authorize=>fail:', fail);
					}
				}, )

				// #endif
			},
			openMap(item) {
				uni.openLocation({
					longitude: parseFloat(item.lng),
					latitude: parseFloat(item.lat),
					success: (res) => {
						console.log('打开成功');
					},
					fail: (err) => {
						console.log(err);
					}
				})
			},
			payNow() {},
			// 取消订单
			orderCancel() {
				uni.showModal({
					title: "确认取消吗？",
					success: ({
						confirm
					}) => {
						stateUpdate({
							id: this.details.id,
							status: this.details.status,
						}).then((resp) => {
							console.log("取消订单", resp);
							if (resp.code == 200) {
								this.initInfo();
							}
						});
					},
				});
			},
			payClick(index) {
				statePay({
					id: this.details.id,
					pay: this.payList[index].value,
				}).then((resp) => {
					console.log("订单支付", resp);
					if (resp.code == 200) {
						if (resp.data.payRes) {
							const {
								timeStamp,
								nonceStr,
								signType,
								paySign
							} = resp.data.payRes;
							uni.requestPayment({
								timeStamp,
								nonceStr,
								package: resp.data.payRes.package,
								signType,
								paySign,
								success: (resp) => {
									uni.showToast({
										icon: "none",
										title: "支付成功",
									});
									this.initInfo();
								},
								fail: (error) => {
									console.log("payment失败", error);
									// uni.showToast({
									//   icon: "none",
									//   title: "支付失败",
									// });
								},
							});
						} else {
							uni.showToast({
								icon: "none",
								title: resp.msg,
							});
						}
					} else {
						uni.showToast({
							icon: "none",
							title: resp.msg,
						});
					}
				});
			},
			// 查看物流
			logisticsNavigate() {
				uni.navigateTo({
					url: "/pages/common/logistics/logistics?id=" + this.details.id,
				});
			},
			// 确认收货
			confirm() {
				uni.showModal({
					title: "确认收货吗？",
					success: ({
						confirm
					}) => {
						if (confirm) {
							stateUpdate({
								id: this.details.id,
								status: this.details.status,
							}).then((resp) => {
								console.log("取消订单", resp);
								if (resp.code == 200) {
									this.initInfo();
								}
							});
						}
					},
				});
			},
		},
		onUnload(){
			if(this.$refs.cancelOrder){
				this.$refs.cancelOrder.destory()
			}
		}
	};
</script>

<style lang="scss" scoped>
	@import './index.scss';
	/deep/.u-line {
		display: none;
	}
	/deep/.u-model__title{
		display: none;
	}
	/deep/.u-popup__content {
		background: none !important;
	}
	/deep/.u-model{
		background: none !important;
	}
	/deep/.u-mode-center-box {
		background: none !important;
	}
	page {
		background-color: #f7f7f7;
	}

	.orderDetails {
		background-color: #ffffff;

		&-state {
			width: 100%;
			box-sizing: border-box;
			padding: 0 30rpx;

			.log {
				padding: 20rpx 0;
				@include border;
				display: flex;
				align-items: center;

				&-icon {
					width: 40rpx;
					height: 35rpx;
					margin-right: 25rpx;
				}

				&-info {
					.desc {
						font-size: 26rpx;
						color: #cd8544;
						line-height: 50rpx;
					}

					.time {
						font-size: 20rpx;
						color: #aaaaaa;
					}
				}
			}

			.user {
				display: flex;
				align-items: center;
				padding: 10rpx 0;

				&-icon {
					width: 36rpx;
					height: 43rpx;
					margin-right: 25rpx;
				}

				&-info {
					font-size: 24rpx;

					.top {
						display: flex;
						align-items: center;
						line-height: 40rpx;

						&-name {
							margin-right: 35rpx;
						}
					}
				}
			}
		}

		&-order {
			border-top: 10rpx solid #f7f7f7;
			border-bottom: 10rpx solid #f7f7f7;

			width: 100%;
			box-sizing: border-box;
			padding: 30rpx 30rpx 0 30rpx;

			.title {
				width: 100%;
				display: flex;
				align-items: center;
				font-size: 30rpx;
				font-weight: bold;

				.icon {
					width: 25rpx;
					height: 29rpx;
					margin-right: 18rpx;
				}
			}

			.bd {
				width: 100%;
				box-sizing: border-box;
				padding: 0 15rpx;

				.pay {
					line-height: 50rpx;
					text-align: right;
					font-size: 26rpx;
					@include border;
					padding: 20rpx 0;
				}

				.oper {
					text-align: right;

					.btn {
						display: inline-block;
						margin: 22rpx 0;
						padding: 10rpx 15rpx;
						font-size: 26rpx;
						color: #e44444;

						border: 1rpx solid #e44444;
						border-radius: 8rpx;
					}
				}
			}
		}

		&-info {
			background-color: #ffffff;
			color: #aaaaaa;
			font-size: 24rpx;
			line-height: 45rpx;
			box-sizing: border-box;
			padding: 15rpx 30rpx;
			letter-spacing: 1rpx;

			.row {
				.copy {
					width: 70rpx;
					display: inline-block;
					font-size: 22rpx;
					text-align: center;
					line-height: 40rpx;
					border: 1rpx solid #181616;
					border-radius: 4rpx;
					margin-left: 30rpx;
				}
			}
		}

		&-oper {
			height: 100rpx;
			width: 100%;
			box-sizing: border-box;
			padding: 0 30rpx;
			display: flex;
			align-items: center;
			position: fixed;
			left: 0;
			bottom: 0;
			background-color: #ffffff;
			justify-content: flex-end;

			.btn {
				padding: 13rpx 18rpx;
				font-size: 30rpx;
				border-radius: 8rpx;
			}

			.check {
				color: #1e1b1b;
				margin-right: 18rpx;

				border: 1rpx solid #cccccc;
			}

			.confirm {
				color: #ffffff;
				background-color: #cd8544;
			}
		}
	}
	.code{
		margin: 30rpx 0;
		display: flex;
		align-items: flex-end;
		justify-content: center;
		font-size: 24rpx;
		.hint{
			margin-bottom: 10rpx;
			margin-right: 10rpx;
		}
		.number{
			font-weight: bold;
			font-size: 50rpx;
			color: $primary-color;
		}
	}
	.self {
		@extend .flex-center;
		flex-direction: column;
		color: #666666;

		.hint {
			@extend .flex-center;
		}

		.detail {
			font-size: 32rpx;
			color: #333;
			text-align: center;
			margin: 30rpx 0;
			width: 400rpx;
			font-weight: bold;
		}

		.distance {
			margin-right: 20rpx;
			color: #999;
		}
	}
</style>
